<template>
  <section>
    <el-alert type="warning" show-icon title="提示：改规则只实用于当前产品，请不要重复设置条件规则，否则只保留第一条。" style="margin-bottom:20px;"></el-alert> 
    <el-form :model="formData" ref="formData" label-width="40px" size="mini">
      <el-form-item v-for="(item, index) in formData.fullCut" :key="index">
        <el-row :gutter="5">
          <el-col :span="5" >
            <el-form-item label="满" :prop="'fullCut.' + index + '.amount'" :rules="{required: true, message: '不能为空', trigger: 'blur'}">
              <el-input type="number" v-model="item.amount"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="减" :prop="'fullCut.' + index + '.price'" :rules="{required: true, message: '不能为空', trigger: 'blur'}">
              <el-input type="number" v-model="item.price"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-button v-if="index !== 0" @click.prevent="removeItem(item)">-</el-button>
            <el-button v-else @click="addItem">+</el-button>
            <el-button :disabled="!goods.id" :loading="loading"  v-if="index === 0" type="primary" @click="submit('formData')">保存</el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </section>
</template>
<script>
  export default {
    props: ['goods'],
    data () {
      return {
        loading: false,
        formData: {
          fullCut: [{amount: '', price: ''}]
        }
      }
    },
    watch: {
      goods () {
        this.formData.fullCut = this.goods.full_cut ? this.goods.full_cut : [{amount: '', price: ''}]
      }
    },
    methods: {
      addItem () {
        this.formData.fullCut.push({
          amount: '',
          price: ''
        })
      },
      removeItem (item) {
        var index = this.formData.fullCut.indexOf(item)
        if (index !== -1) {
          this.formData.fullCut.splice(index, 1)
        }
      },
      submit (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$http.put('/goods/' + this.goods.id, {full_cut: this.formData.fullCut})
            .then((response) => {
              this.loading = false
              this.formData = {fullCut: response.data.full_cut}
              this.$message.success('保存成功')
            }).catch((error) => {
              this.loading = false
              console.log(error)
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    }
  }
</script>
